#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "sqlite3.h"
#include "db.h"
extern recv_cli_t user;
extern int grid[2];

unsigned int photo_size;

//select用户密码 从用户信息表
static int get_info(void *pwd,int argc,char **argv,char **azColName)
{
	char *p = (char *)pwd;
	strcpy(p,argv[0]);
	return 0;
}


//生成验证码
char *randdom()
{
	static char arr[7];
	char str[10] = {'0','1','2','3','4','5','6','7','8','9'};
	int i = 0;
	char a = 0;
	srand((unsigned)time(NULL));
	for(i = 0;i < 6; i++)
	{
		a = rand()%10;
		arr[i] = str[a];
	}
	arr[i] = '\0';
	return arr;
}



//变量带有db 代表数据库数据

//order_reg
//参数：user(struct) 
//功能:快递员登录成功之后，生成用户结构体信息
//     将用户手机号，订单号，柜号，验证码插入到数据库表中
char * order_reg(int num)
{
	printf("%s  %s  %s  %s\n",user.business,user.post,user.phone,user.info);
	sqlite3 *db;
	char *zErrmsg;
	int ret = sqlite3_open("Cabinet.db",&db);
	if(NULL == db)
	{
		puts("open db error.");
		return NULL;
	}
	printf("数据库打开成功.\n");
	static char *code; 
	code = randdom();
	printf("%s\n",code);
	char sql[300];
	memset(sql,0,sizeof(sql));
	//将结构体中信息插入到数据库中
	sprintf(sql,"insert into send(business,post,phone,info,code,grid) values('%s', '%s','%s','%s','%s','%d')",user.business,user.post,user.phone,user.info,code,num);
	sqlite3_exec(db,sql,NULL,NULL,&zErrmsg);
	
	memset(sql,0,sizeof(sql));
	sprintf(sql,"update box set status = '1' where code = '%d'",num);
	sqlite3_exec(db,sql,NULL,NULL,&zErrmsg);
	
	printf("%s\n",sql);
	printf("用户订单插入成功.\n");
	sqlite3_close(db);
	printf("数据库关闭.\n");
#if 0
	char py[50] = {0};
	sprintf(py,"python box.py %s %s",user.phone,code);
	if (system(py)<0)
	{
		printf("exec error");
	}
#endif
	return code;
}

//order_reg_auto
//功能:快递员登录成功之后，生成用户结构体信息,选择了自动模式
//     根据解析结果，将用户手机号，订单号，柜号，验证码插入到数据库表中
int order_reg_auto()
{
	int fd = open("./info.txt",O_RDONLY);
	if(fd == -1)
	{
		printf("open info.txt error\n");
		return -1;
	}
	char ordernum[128] = {0};
	read(fd, ordernum, sizeof(ordernum));
	printf("ordernum: %s\n", ordernum);

	char *phonenum = strtok(ordernum, "#");
    phonenum = strtok(NULL, "#");
    strncpy(user.phone, phonenum, strlen(phonenum));
    
	printf("user.phone: %s\n", user.phone);

    strncpy(user.info, ordernum, strlen(ordernum));
    printf("user.info: %s\n", user.info);


    int num = get_grid();

#if 1

	sqlite3 *db;
	char *zErrmsg;
	int ret = sqlite3_open("Cabinet.db",&db);
	if(NULL == db)
	{
		puts("open db error.");
		return -1;
	}
	printf("数据库打开成功.\n");
	static char *code; 
	code = randdom();
	printf("%s\n",code);
	char sql[300];
	memset(sql,0,sizeof(sql));
	//将结构体中信息插入到数据库中
	sprintf(sql,"insert into send(business,post,phone,info,code,grid) values('%s', '%s','%s','%s','%s','%d')",user.business,user.post,user.phone,user.info,code,num);
	sqlite3_exec(db,sql,NULL,NULL,&zErrmsg);
	puts(sql);
	memset(sql,0,sizeof(sql));
	sprintf(sql,"update box set status = '1' where code = '%d'",num);
	sqlite3_exec(db,sql,NULL,NULL,&zErrmsg);
	
	printf("%s\n",sql);
	printf("用户订单插入成功.\n");
	sqlite3_close(db);
	printf("数据库关闭.\n");
#if 0
	char py[50] = {0};
	sprintf(py,"python box.py %s %s",user.phone,code);
	if (system(py)<0)
	{
		printf("exec error");
	}
#endif
	return num;
#endif
}
//用户取件成功，信息擦除
int delete_user(char *phone,char *info)
{
	char dbphone[13] = {0};
	sqlite3 *db;
	char *zErrmsg;
	int ret = sqlite3_open("Cabinet.db",&db);
	if(NULL == db)
	{
		puts("open db error.");
		return -1;
	}
	printf("数据库打开成功.\n");

	char sql[300];
	memset(sql,0,sizeof(sql));
	//用户取件成功，信息擦除
	sprintf(sql,"delete from send where code = '%s' ",info);
	if(SQLITE_OK != sqlite3_exec(db,sql,NULL,NULL,&zErrmsg))
	{
		printf("sqlite_exec run error.\n");
		return -1;
	}
	printf("%s\n",sql);
	printf("用户取件成功，该条取件信息已删除.\n");
	sqlite3_close(db);
	printf("数据库关闭\n");
	return 1;
}

//函数名：user_log
//参数：phone：手机号 info：验证码
//功能：用户取件
//       首先比对手机号是否在send数据库表中，
//       在判断验证码的正确性
char *user_log(char *phone,char *info)
{
	static char dbpost[5];
	printf("phone:%s\tinfo:%s\n",phone,info);
	char dbphone[13] = {0};
	char dbinfo[13] = {0};
	sqlite3 *db;
	char *zErrmsg;
	int ret = sqlite3_open("Cabinet.db",&db);
	if(NULL == db)
	{
		puts("open db error.");
		return NULL;
	}
	printf("数据库打开成功.\n");
	
	char sql[300];
	memset(sql,0,sizeof(sql));
	//char dbpost[5] = {0};

	sprintf(sql,"select code from send where phone = '%s'",phone);
	sqlite3_exec(db,sql,get_info,dbinfo,&zErrmsg);
	printf("%s  %s\n",info,dbinfo);
	if(0!= strcmp(dbinfo,info))
	{
		printf("用户验证码错误.\n");
		return NULL;
	}
	else
	{
		printf("用户验证码比对成功.\n");
		sprintf(sql,"select phone from send where phone = '%s'",phone);
		sqlite3_exec(db,sql,get_info,dbphone,&zErrmsg);
		printf("%s  %s\n",phone,dbphone);
		if(0 != strcmp(dbphone,phone))
		{
			printf("用户手机号错误.\n");
			return NULL;
		}	
		else
		{
			printf("用户手机号比对成功.\n");
			
			sprintf(sql,"select grid from send where phone = '%s'",phone);
			if(SQLITE_OK == sqlite3_exec(db,sql,get_info,dbpost,&zErrmsg))
			{
				printf("%s\n",dbpost);
			}
			else{
				return NULL;
			}
		}
		sqlite3_close(db);
		printf("数据库关闭\n");
		delete_user(phone,dbinfo);
		return dbpost;
	}
}

//函数名：courier_log
//参数：phone：手机号 info：密码
//功能：快递员登录
//      首先比对手机号是否在recv数据库表中，
//      在判断验证码的正确性
int courier_log(char *phone,char *info)
{
	printf("phone:%s\tinfo:%s\n",phone,info);
	char dbphone[13] = {0};
	sqlite3 *db;
	char *zErrmsg;
	int ret = sqlite3_open("Cabinet.db",&db);
	if(NULL == db)
	{
		puts("open db error.");
		return -1;
	}
	printf("数据库打开成功.\n");

	char sql[300];
	char box_code[5] = {0};
	memset(sql,0,sizeof(sql));
		
	sprintf(sql,"select status from box where code = '0'");
	sqlite3_exec(db,sql,get_info,box_code,&zErrmsg);
	grid[0] = atoi(box_code);
	
	memset(sql,0,sizeof(sql));
	sprintf(sql,"select status from box where code = '1'");
	sqlite3_exec(db,sql,get_info,box_code,&zErrmsg);
	grid[1] = atoi(box_code);
	
	memset(sql,0,sizeof(sql));
	sprintf(sql,"select phone from recv where phone = '%s'",phone);
	sqlite3_exec(db,sql,get_info,dbphone,&zErrmsg);
	printf("%s %s\n",phone,dbphone);
	if(0 != strcmp(dbphone,phone))
	{
		sqlite3_close(db);
		printf("帐号不存在.\n");
		return -1;
	}
	else
	{
		printf("快递员帐号比对成功.\n");
		char dbinfo[13] = {0};
		sprintf(sql,"select code from recv where phone = '%s'",phone);
		sqlite3_exec(db,sql,get_info,dbinfo,&zErrmsg);
		printf("%s %s\n",info,dbinfo);
		if(0!= strcmp(dbinfo,info))
		{
			printf("密码错误.\n");
			goto A;

		}
		printf("快递员密码比对成功.\n");
		sqlite3_close(db);
		printf("数据库关闭\n");
		goto B;

	}
	A:return -1;
	B:return 0;
}

/*
 * 解析函数: recv_cmd()
 * 入参：eg:1#1111#13900000000#1234
 * 返回值：结构体 {字符串1 2 3 4}
 */
recv_cli_t split(char *buf)
{
	char *p;

	memset(&user,0,sizeof(user));
	/*分解字符串*/
	p = strtok(buf, "#");
	puts(p);
	strcpy(user.business, p);
	p = strtok(NULL, "#");
	puts(p);
	if (NULL != p)
	{
		strcpy(user.post, p);
	}
	if(p = strtok(NULL, "#"));
	puts(p);
	strcpy(user.phone, p);
	
	if(p = strtok(NULL, "#"));
	puts(p);
	strcpy(user.info, p);



	return user;
}



/*int  recv_package(char *num,char *recv_num)
 * 函数名：recv_package
 *函数功能:实现用户的取件
 *函数参数：
 		num:客户电话号码
		recv_num:取件验证码
 *函数返回值:
 		成功：0
		失败：-1
*/
int  recv_package(char *num,char *recv_num)
{
	sqlite3 *db;
	char *zErrmsg;
	int ret = sqlite3_open("Cabinet.db",&db);
	if(NULL == num || NULL == recv_num)
	{
		printf("parameter error!\n");
		return -1;

	}
	printf("transfer parameter success!\n");
	printf("%s\n",num);
	printf("%s\n",recv_num);

	//根据用户电话号码，验证码在数据库中查找对应的格口号
	char *send_nump=user_log(num,recv_num);
	if(NULL==send_nump)
	{
		printf("user_log error!\n");
		return -1;
	}
	printf("user_log success:格口号为=%s\n",send_nump);
	
	int code = atoi(send_nump);
	grid[code] = 0;
	
	char sql[300];
	memset(sql,0,sizeof(sql));
	sprintf(sql,"update box set status = '0' where code = '%d'",code);
	sqlite3_exec(db,sql,NULL,NULL,&zErrmsg);

	return code;

}

/*
	用户投递函数
	入参：手机号 订单号
	返回值：
*/
int courier_send(char *num, char *recv_num)
{
	if(NULL == num || NULL == recv_num)
	{
		printf("快递员投递函数入参错误！\n");
		return -1;
	} 
	if(strcmp(num, "auto") == 0)
	{
		printf("快递员选择了自动模式\n");
		photo_size = atoi(recv_num);
		printf("photo_size = %u\n", photo_size);
		return -2;
	}
    return get_grid();
    #if 0
	int i=0;
	char buf[30]={0};
	for(;i<2;i++)
	{
		if(0 == grid[i])
		{
			break;
		}                                                                   
	}
	if( i > 1 )
	{
		printf("没有空格子放快递\n");
		i = -1;
	}
	else
	{
		grid[i] = 1;
	}
    
	return i;
    #endif
}
#if 0
int get_qrcode(char *buf)
{
	char *p;
	char *tmp = (char *)malloc(photo_size + 48);

	memset(&user,0,sizeof(user));
	/*分解字符串*/
	p = strtok(buf, "#");
	puts(p);
	strcpy(user.business, p);
	p = strtok(NULL, "#");
	puts(p);
	if (NULL != p)
	{
		strcpy(user.post, p);
	}
	if(p = strtok(NULL, "#"))
		return -1;
	puts(p);
	strcpy(user.phone, p);
	
	if(p = strtok(NULL, "#"))
		return -1;
	puts(p);
	strncpy(tmp, p, photo_size);
	save_qrcode(tmp);

	return 0;
}
#endif

int save_qrcode(char *data)
{
	puts("hhhh  save_qrcode  hhhhhh");

	int fd = open("./qrcode.jpg", O_WRONLY | O_CREAT, 0644);
	unsigned int ret = write(fd, data, photo_size);
	if(ret != photo_size)
		puts("recv error");
	close(fd);

	puts("hhhh  save_qrcode  hhhhhh");
	return 0;
}

int get_grid()
{
    int i=0;
	for(;i<2;i++)
	{
		if(0 == grid[i])
		{
			break;
		}                                                                   
	}
	if( i > 1 )
	{
		printf("没有空格子放快递\n");
		i = -3;
	}
	else
	{
		grid[i] = 1;
	}
	return i;
}
